//
//  QXStatus.swift
//  QXWeibo
//
//  Created by QinXin on 15/6/30.
//  Copyright © 2015年 labi3285_Lab. All rights reserved.
//

import UIKit
import SDWebImage

private let wb_home_timeline_url = "2/statuses/home_timeline.json"

class QXStatus: NSObject {
    
    /// 创建时间
    var created_at: String?
    /// 微博id
    var id: Int = 0
    /// 微博内容
    var text : String?
    /// 微博来源
    var source: String?
    /// 配图（数组）
    var pic_urls: [[String: String]]? {
        didSet {
            imageURLs = [NSURL]()
            largeImageURLs = [NSURL]()

            // 执行到这里表示pic_urls 里面有数据
            for dic in pic_urls! {
                
                let urlString = dic["thumbnail_pic"]!
                imageURLs?.append(NSURL(string: urlString)!)
                
                let largeString = urlString.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
                largeImageURLs?.append(NSURL(string: largeString)!)
            }
        }
    }
    /// 用户模型
    var user: QXUser?
    /// 配图的网址数组（有的微博没有图片，因此这里不要初始化）
    var retweeted_status: QXStatus?
    
    // 原创图片地址
    private var imageURLs: [NSURL]?
    
    // 单元格的配图（原创或转发）
    var allImageURLs: [NSURL]? {
        return retweeted_status?.imageURLs != nil ? retweeted_status?.imageURLs : imageURLs
    }
    
    // 大图
    var largeImageURLs: [NSURL]?
    // 原创或转发
    var allLargeImageURLs: [NSURL]? {
        return retweeted_status?.largeImageURLs != nil ? retweeted_status?.largeImageURLs : largeImageURLs
    }
    
    static let properties = [
        "created_at",
        "id",
        "text",
        "source",
        "pic_urls",
        "user",
    ]
    
    init(dic: [String: AnyObject]) {
        
        super.init() // 这句必须（KVC）
        
        for key in QXStatus.properties {
            if dic[key] == nil || key == "user" || key == "retweeted_status"{
                continue
            }
            setValue(dic[key], forKey: key)
        }
        
        if let userDic = dic["user"] as? [String: AnyObject] {
            user = QXUser(dic: userDic)
        }
        
        if let statusDic = dic["retweeted_status"] as? [String: AnyObject] {
            retweeted_status = QXStatus(dic: statusDic)
        }
        
    }
    
    override var description: String {
        let dic = dictionaryWithValuesForKeys(QXStatus.properties)
        return "\(dic)"
    }
    
    
    /// 从网络获取数据模型
    class func loadStatus(since_id: Int, max_id: Int, done: (statuses: [QXStatus]?, error: NSError?) -> () ) {
        
        assert(sharedAccount != nil, "账户不能为空，要先登录")
        
        var params = [
            "access_token": sharedAccount!.access_token,
        ]
        
        if since_id > 0 {
            params["max_id"] = "0"
            params["since_id"] = "\(since_id)"
        }
        
        if max_id > 0 {
            params["since_id"] = "0"
            params["max_id"] = "\(max_id - 1)"   // !!!!!!!!
        }
        
        QXNetworking.sharedNetworking().GET(wb_home_timeline_url, parameters: params, success: { (_, JSON) -> Void in
            
            // JSON 转 模型
            if let arr = JSON["statuses"] as? [[String: AnyObject]] {
                var marr = [QXStatus]()
                for dic in arr {
                    marr.append(QXStatus(dic: dic))
                }
                
                // 解析到数据，交给缓存方法进一步处理
                cacheWebImages(marr, done: done)
                return
            }
            
            // 走到这里表示解析失败
            done(statuses: nil, error: nil)
            
            }) { (_, error) -> Void in
                // 访问出错
                done(statuses: nil, error: error)
        }
    }
    
    private class func cacheWebImages(statuses: [QXStatus], done: (statuses: [QXStatus]?, error: NSError?) -> ()) {
        
        if statuses.count == 0 {
            done(statuses: nil, error: nil)
            return
        }
        
        // 这个group用于在缓存所有图片之后执行某个操作
        let group = dispatch_group_create()
        
        for status in statuses {
            
            // 原创微博的图片
            if status.allImageURLs == nil || status.allImageURLs!.isEmpty {
                continue
            }
            
            for url in status.allImageURLs! {
                
                // 异步操作要添加到任务组中
                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (_, _, _, _, _) in
                    dispatch_group_leave(group)
                })
            }
            
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
            done(statuses: statuses, error: nil)
        })
        
    }
    
}
